require 'rubygems'
require 'jdbc_adapter'
require 'active_record'
require 'java'
require 'hazelcast.jar'
require 'app/models/cpu'
require 'app/models/sysinfo'
require 'app/models/event'
Dir["lib/*.jar"].each { |jar| require jar }

import com.hazelcast.core.Hazelcast
import com.hazelcast.core.MembershipListener
import com.hazelcast.core.MembershipEvent

import java.util.Map
import java.util.Collection

cluster = Hazelcast.getCluster();
puts "I am an engine"

map_cpu = Hazelcast.get_map "cpu"
cpu1 = map_cpu.get("1")
cpu1 = Marshal.load(cpu1)

map_sys_info = Hazelcast.get_map "sys_info"
si = map_sys_info.get("1")
# si = Marshal.load(si)

line = 'Cluster time ' + cluster.get_cluster_time.to_s
puts line

while !line.eql? 'quit'
  print '> '
  line = gets.chop
  # puts "Command: #{line}"
  if line.eql? 'cpu 1'
    puts "Vendor: ...." + cpu1.vendor
	puts "Model: ....." + cpu1.model
	puts "Mhz: ......." + cpu1.mhz
	puts "Cache size: " + cpu1.cache_size
  end
  
  if line.eql? 'sys info'
    puts "CPUs: ....." + si.cpu_num
	puts "Total memory: " + si.mem_total
	puts "Memory used: " + si.mem_used
  end
end

Process.exit

# events

cluster.add_membership_listener {|event| 
  member = event.getMember
  address = member.get_inet_address.to_s
  port = member.get_port
  address = address.gsub("/", "")
  type = event.get_event_type
  type_text = "NOT_DEFINED"
  if type == 1
    type_text = "MEMBER_ADDED"
  end
  if type == 3
    type_text = "MEMBER_REMOVED"
  end
  
  #puts "Node: " + address + " status " + type_text
  log_event(address, port, type_text)
}

# DB config to be moved in config
def log_event(address, port, type)
  puts "Node: " + address + " status " + type
  ActiveRecord::Base.establish_connection(
    :adapter  => 'jdbcmysql',
	:database => 'mongrid',
	:username => 'root',
	:password => 'asdf',
	:host     => 'localhost')
	
  e = Event.new
  e.address = address
  e.port = port
  e.type = type
  e.event_time = Time.now
  e.save
end